package xyz.xxpc.springcloud.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class ClientHandler extends Thread {

    private final Socket client;

    /**
     * 实例化 客户端连接处理类
     *
     * @param client
     */
    public ClientHandler(Socket client) {
        this.client = client;
    }

    @Override
    public void run() {
        boolean process = true;
        // 获取到输入流的读取器
        BufferedReader in = null;
        try {
            in = new BufferedReader(
                    new InputStreamReader(client.getInputStream())
            );
            while (true) {
                String line = in.readLine(); // 读取一行请求头信息
                if (line == null) {
                    // 没有请求头 直接关闭连接
                    process = false;
                    break;
                }
//                System.out.println(line);
                break;
//                if (line == null || line.length() == 0) {
//
//                }
            }
            if (process) {
                // 输出内容到客户端
                PrintWriter out = new PrintWriter(client.getOutputStream());
                StringBuffer sb = new StringBuffer();
                sb.append("hello client!" + System.currentTimeMillis() + "<br>\n");
                int code = 200;

                try {

                    sb.append("current user count:1" +DbTool.userCount());
                } catch (Exception e) {
                    code = 500;
                    sb.append(e.getMessage());
                    e.printStackTrace();
                }
                // 输出头
                out.println("HTTP/1.1 " + code);
                out.println("Content-Type: text/html;charset=utf-8");
                out.println();
                // 输出内容
                out.println(sb.toString());
                out.flush();
                out.close();
            }
            // 关闭所有的资源
            in.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
